﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;
using System.Xml.XPath;
using System.Collections.Generic;

namespace EF.Util
{
    public class XmlHelp
    {
        protected string StrXmlFile;
        protected XmlDocument doc = new XmlDocument();

        public XmlHelp(string path)
        {
            Open(path);
        }

        #region 加载xml文件

        public void Open(string xmlFile)
        {
            try
            {
                doc.Load(xmlFile);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            StrXmlFile = xmlFile;
        }

        #endregion

        #region 返回XmlNodeList

        ///<summary>   
        /// 根据搜索条件返回节点列表
        ///</summary>  
        ///<param name="xpath">搜索的xpath</param>
        public XmlNodeList GetList(string xpath)
        {
            XmlNodeList xnl = doc.SelectNodes(xpath);

            return xnl;
        }

        #endregion

        #region 返回XmlNode
        ///<summary>   
        /// 根据搜索条件返回节点
        ///</summary>  
        ///<param name="xpath">搜索的xpath</param>
        public XmlNode GetSingleNode(string xpath)
        {
            XmlNode xn = doc.SelectSingleNode(xpath);

            return xn;
        }

        #endregion

        #region 添加一条记录
        ///<summary>   
        /// 插入一条记录
        ///</summary>  
        ///<param name="Par">要插入的位置</param>
        ///<param name="Element">要插入节点的名称</param>
        ///<param name="Context">插入节点的InnerText(""为空)</param>
        ///<param name="ht">要插入节点的属性列表 (null为空)</param>
        public void Insert(string Par, string Element, string Context, Hashtable ht)
        {

            XmlNode objNode = doc.SelectSingleNode(Par);
            XmlElement objElement = doc.CreateElement(Element);
            objElement.SetAttribute("id", returnMax().ToString());
            if (ht != null)
            {
                foreach (DictionaryEntry dic in ht)
                {
                    objElement.SetAttribute(dic.Key.ToString(), dic.Value.ToString());
                }
            }

            objElement.InnerText = Context;
            objNode.AppendChild(objElement);
            Save();

        }
        #endregion

        #region 删除一条记录
        ///<summary>   
        /// 删除一条记录
        ///</summary>  
        ///<param name="xpath">删除节点的xpath</param>
        public void Delete(string xpath)
        {
            string par = doc.SelectSingleNode(xpath).ParentNode.Name;
            doc.SelectSingleNode(par).RemoveChild(doc.SelectSingleNode(xpath));
            Save();
        }

        #endregion

        #region 修改一条记录
        ///<summary>   
        ///修改一条记录
        ///</summary>  
        ///<param name="xpath">xpath</param>
        ///<param name="context">innertxt</param>
        ///<param name="ht">要修改的属性列表</param>
        public bool Modify(string xpath, string context, Hashtable ht)
        {
            if (IsExist(xpath))
            {
                XmlElement objNode = (XmlElement)doc.SelectSingleNode(xpath);
                if (ht != null)
                {
                    foreach (DictionaryEntry dic in ht)
                    {
                        objNode.SetAttribute(dic.Key.ToString(), dic.Value.ToString());
                    }
                }
                objNode.InnerText = context;
                Save();
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 判断重名
        /// <summary>
        /// 判断是否重名  true为重名
        /// </summary>
        /// <param name="xpath">xpath</param>
        /// <returns></returns>
        public bool IsExist(string xpath)
        {
            //Open(strXmlFile);
            XmlNodeList list = doc.SelectNodes(xpath);
            if (list.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region  返回记录总数
        /// <summary>
        /// 返回记录总数
        /// </summary>
        /// <param name="xpath">xpath</param>
        /// <returns></returns>
        public int getTotalCount(string xpath)
        {
            XmlNodeList list = doc.SelectNodes(xpath);
            return list.Count;

        }
        #endregion

        #region 保存xml文档
        ///<summary>   
        /// 保存xml文档
        ///</summary>  
        public void Save()
        {
            try
            {
                doc.Save(StrXmlFile);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region  分页
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="intPageSize">每页显示几条记录</param>
        /// <param name="intPageIndex">当前第几页</param>
        /// <param name="xpath">搜索条件 例如("//Setting[contains(@name,'b')]")意思为Setting节点name属性含有b的所有Node</param>
        /// <param name="sort">排序字段(节点名或者属性名  属性名前加@)</param>
        /// <param name="boolSort">true为降序,false为升序    null为无</param>
        /// <param name="isNumber">true为按数字方式排列false按字符串方式排列</param>
        /// <returns></returns>
        public List<XmlNode> XmlMinutePage(int intPageSize, int intPageIndex, string xpath, string sort, bool boolSort, bool isNumber)
        {

            int start = intPageSize * intPageIndex - intPageSize + 1;
            int end = intPageIndex * intPageSize;
            XPathNavigator nav = doc.CreateNavigator();
            XPathExpression exp = nav.Compile(xpath);
            if (!(sort.Equals("") && boolSort == null))
            {
                if (boolSort)
                {
                    if (isNumber)
                    {
                        exp.AddSort(sort, XmlSortOrder.Descending, XmlCaseOrder.None, "", XmlDataType.Number);
                    }
                    else
                    {
                        exp.AddSort(sort, XmlSortOrder.Descending, XmlCaseOrder.None, "", XmlDataType.Text);
                    }
                }
                else
                {
                    if (isNumber)
                    {
                        exp.AddSort(sort, XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
                    }
                    else
                    {
                        exp.AddSort(sort, XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text);
                    }
                }
            }
            XPathNodeIterator nodeIter = nav.Select(exp);

            List<XmlNode> list = new List<XmlNode>();
            int i = 1;
            while (nodeIter.MoveNext())
            {

                if (i >= start && i <= end)
                {
                    XmlNode node = ((IHasXmlNode)nodeIter.Current).GetNode();
                    string str = nodeIter.Current.GetAttribute("id", string.Empty);
                    list.Add(node);
                }
                else if (i > end)
                {
                    break;
                }
                i++;
            }
            return list;
        }

        public List<XmlNode> XmlMinutePage(int intPageSize, int intPageIndex, string xpath)
        {
            return XmlMinutePage(intPageSize, intPageIndex, xpath, "", false, false);
        }
        #endregion

        #region ID自动加1
        public int returnMax()
        {
            XmlNode xn = GetSingleNode("//Setting[last()]");
            return int.Parse(xn.Attributes.GetNamedItem("id").Value.ToString()) + 1;
        }
        #endregion

        #region 销毁对象
        /// <summary>
        /// 销毁XmlDocument
        /// </summary>
        public void Dispose()
        {
            doc = null;
            GC.Collect();
        }
        #endregion

    }
}
